const feedbackDao = require('../dao/feedbackDao');
const async = require('async');
const _ = require('lodash');
const errorTip = require('../util/errorTip');
const request = require("../util/request");
const baseModel = require('./baseModel');
const moment = require('moment');

const FeedbackModel = Object.assign({

	dao: feedbackDao,

	save : function (req,callback) {
		
		_.each(req.body,function(value,key){
			req.sanitizeBody(key).trim();
		});		

		req.checkBody({
			content: {
				notEmpty: {
					errorMessage: errorTip['不可为空'].message
			    }
			},
		});

		req.getValidationResult().then((result) => {
			
			if(result.isEmpty()){
				const { userId } = req.body;
				async.waterfall([
					(callback) => {

						this.getList({query: {userId}}, (err, ret) => {
							if(!err){
								let hasPosted = false;
								_.each(ret.results, (feed) => {
									if( moment().isSame(moment(feed.createdTime), 'day') ){
                                        hasPosted = true;
                                        callback({code:10010,message:'同一天内您只能进行一次反馈',warningType:'alert'});
										return false;
									}
								});
								if(hasPosted){
									return;
								}
							}
							callback(err);

						});
					},
					(callback) => {
                        let doc = _.clone(req.body);
                        doc.createdTime = moment().toISOString();

                        feedbackDao.save(doc,(err,doc) => {
                            callback(err,doc);
                        });
					}
				],
				(err, doc) => {
					callback(err, doc);
				});

			}
			else{
				let err = result.array({useFirstErrorOnly: true})[0];
				callback(err);
			}

		});

	},

	getFeedbackList: function(req,callback){

		const pipeLine = [
			// Stage 1
			{
				$lookup: {
				    "from" : "user",
				    "localField" : "userId",
				    "foreignField" : "_id",
				    "as" : "user"
				}
			},
			
			// Stage 2
			{
				$unwind: {
				    path : "$user",
				    preserveNullAndEmptyArrays : false // optional
				}
			},

		];

		this.getList(req, pipeLine, (err, ret) => {
			callback(err, ret);
		});	

	},

}, baseModel);

module.exports = FeedbackModel;